#include "cell_record.h"
#include "ui_cell_record.h"

Cell_record::Cell_record(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Cell_record)
{
    ui->setupUi(this);
    ui->tableView->setModel(&m_model);
    ui->tableView->setEditTriggers(QAbstractItemView::NoEditTriggers);//不能直接更改表格中的元素
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);//每次选中会选中一行
    m_model.setHorizontalHeaderLabels(QStringList{"id","图书id","用户id","借阅起始时间","借阅结束时间"});
    ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);//让m_model占满tableView
}

Cell_record::~Cell_record()
{
    delete ui;
}

void Cell_record::initPage(QString strCondition)
{
    auto l=Sqlmgr::getinstance()->getRecord(strCondition);
    m_model.clear();
    m_model.setHorizontalHeaderLabels(QStringList{"id","图书id","用户id","借阅起始时间","借阅结束时间"});
    for(int i=0;i<l.size();i++)
    {
        QList<QStandardItem*> items;
        for(int j=0;j<l[i].size();j++)
        {
            items.append(new QStandardItem(l[i][j]));
        }
        m_model.appendRow(items);
    }
}

void Cell_record::on_btn_clear_clicked()
{
    Sqlmgr::getinstance()->clearRecord();
    initPage();
}





void Cell_record::on_pushButton_clicked()
{
    int r=ui->tableView->currentIndex().row();
    if(r<0)
    {
        return;
    }
    auto id=m_model.item(r,1)->text().toUInt();
    QString Bookname=Sqlmgr::getinstance()->searchBook(id);
    Dlg_BookGetAndSet dlg;
    dlg.setType(false,Bookname);
    dlg.setBookId(id);
    int ret=dlg.exec();
    QMessageBox::information(nullptr,"信息",ret?"归还成功":"归还失败");
    if(ret)
    {
        initPage();
    }
}


void Cell_record::on_le_search_textChanged(const QString &arg1)//搜索图书id
{
    if(!arg1.isEmpty())
    {
        QString strCondition=QString("where bookid=%1").arg(arg1.toUInt());
        initPage(strCondition);
    }
    else
    {
    initPage();
    }

}


void Cell_record::on_btn_search_clicked()
{
    int id=ui->le_search->text().toUInt();
    QString strCondition=QString("where userid=%1").arg(id);
    initPage(strCondition);
}

